package com.core.data;

import org.springframework.util.StringUtils;

/**
 * @author gang
 */
public interface IMapper<T extends BaseEntity> {
    int deleteByPrimaryKey(String id);

    int insert(T record);

    int insertSelective(T record);

    T selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(T record);

    int updateByPrimaryKey(T record);

    /**
     * 根据ID是否为判断是调用插入还是更新方法
     *
     * @param model 需要操作的实体类
     * @return 影响的行数
     */
    default int save(T model) {

        if (StringUtils.isEmpty(model.getId())) {
            return this.insertSelective(model);
        } else {
            int i = this.updateByPrimaryKey(model);
            if (i <= 0) {
                T db = this.selectByPrimaryKey(model.getId());
                if (db == null) {
                    return this.insertSelective(model);
                }
                return 0;
            } else {
                return i;
            }
        }
    }
}
